// Created by carolsail

import { ENUM_AUDIO_CLIP, ENUM_UI_TYPE } from "../Enum";
import { StaticInstance } from './../StaticInstance';
import AudioManager from "../manager/AudioManager";
import BaseLayer from "./Baselayer";
import SdkManager from "../manager/SdkManager";
import ToastManager from "../manager/ToastManager";
import ResourceManager from "../manager/ResourceManager";
import DataManager from "../manager/DataManager";
import UIScrollControl from "../plugins/UIScrollControl";
import PoolManager from "../manager/PoolManager";

const { ccclass, property } = cc._decorator;

@ccclass
export default class RankLayer extends BaseLayer {

    panel: cc.Node = null
    btnClose: cc.Node = null
    btnShare: cc.Node = null
    menus: cc.Node = null
    menuIndex: number = 0
    mainScroll: cc.Node = null
    tip: cc.Node = null
    item: cc.Node = null

    onLoad() {
        this.panel = cc.find('style/panel', this.node)
        this.btnClose = cc.find('btn_close', this.panel)
        this.btnShare = cc.find('btn_share', this.panel)
        this.btnClose.on('click', this.onCloseClick, this)
        this.btnShare.on('click', this.onShareClick, this)
        this.menus = this.panel.getChildByName('menus')
        for (let i = 0; i < this.menus.children.length; i++) {
            const menu = this.menus.children[i]
            if (!menu.hasEventListener('click')) menu.on('click', () => { this.onMenuClick(i) }, this)
        }
        this.mainScroll = this.panel.getChildByName('main_scroll')
        this.tip = this.panel.getChildByName('tip')
        this.item = PoolManager.instance.getNode('RankItem')
    }

    onDestroy() {
        this.btnClose.off('click', this.onCloseClick, this)
        this.btnShare.off('click', this.onShareClick, this)
    }

    onEnable() {
        this.zoomIn(this.panel)
        this.rendorMenu()
        this.rendorScroll()
        SdkManager.instance.getRank()
        SdkManager.instance.showInterstitialAd()
        SdkManager.instance.toggleCustomRowAd(true)
        this.rendorPowerTimer()
    }

    onDisable() {
        SdkManager.instance.toggleCustomRowAd(false)
        this.menuIndex = 0
    }

    rendorMenu() {
        for (let i = 0; i < this.menus.children.length; i++) {
            const menu = this.menus.children[i]
            let hex = i == this.menuIndex ? '#F7AD54' : '#69BCF9'
            menu.color = new cc.Color().fromHEX(hex)
        }
        this.mainScroll.opacity = this.menuIndex == 0 ? 0 : 255
        this.tip.active = !(this.menuIndex == 0)
    }

    rendorScroll() {
        const json = ResourceManager.instance.getJson('users')
        let users = JSON.parse(JSON.stringify(json))
        const you = {
            "nickName": '你',
            "winCount": DataManager.instance.countWin,
            "loseCount": DataManager.instance.countLose
        }
        users.push(you)
        // 计算排序
        users.sort((a: any, b: any) => {
            const aw = a['winCount'] * DataManager.instance.scoreWin - a['loseCount'] * DataManager.instance.scoreLose
            const bw = b['winCount'] * DataManager.instance.scoreWin - b['loseCount'] * DataManager.instance.scoreLose
            if (aw > bw) {
                return -1
            } else if (aw < bw) {
                return 1
            } else {
                return 0
            }
        })
        const index = users.findIndex((user: any) => user.nickName == '你')
        // 前二十
        users = users.slice(0, 19)
        // 格式化
        let nUsers = []
        for (let i = 0; i < users.length; i++) {
            const user = users[i]
            nUsers.push({
                nickname: user.nickName,
                rank: i + 1,
                avatar: '',
                score: user.winCount * DataManager.instance.scoreWin - user.loseCount * DataManager.instance.scoreLose
            })
        }
        // 我的排行
        let myRank = []
        if (index <= 19) {
            myRank = [{ nickname: '你', rank: index + 1, avatar: '', score: nUsers[index].winCount * DataManager.instance.scoreWin - nUsers[index].loseCount * DataManager.instance.scoreLose }]
        }
        const res = {
            top: nUsers,
            my: myRank
        }
        // 排序
        const top = res['top']
        const my = res['my']
        let isScrollTop = false
        this.mainScroll.getComponent(UIScrollControl).init(this.item, top.length, cc.size(530, 105), 0, (node: cc.Node, index: number) => {
            if (!isScrollTop) {
                isScrollTop = true
                this.mainScroll.getComponent(cc.ScrollView).scrollToTop()
            }
            const data = top[index]
            // 名次
            const rank = node.getChildByName('rank')
            rank.getChildByName('icon_rank1').active = false
            rank.getChildByName('icon_rank2').active = false
            rank.getChildByName('icon_rank3').active = false
            rank.getChildByName('label').getComponent(cc.Label).string = `${data.rank}`
            if (data.rank <= 3) rank.getChildByName(`icon_rank${data.rank}`).active = true
            // 昵称
            const nickname = node.getChildByName('nickname')
            nickname.getComponent(cc.Label).string = `${data.nickname}`
            // 闯关进度
            const msg = node.getChildByName('tip')
            msg.getComponent(cc.Label).string = `累计积分：${data.score}`
        }, (scroll: cc.ScrollView) => {
            scroll.scrollToTop()
        })
        // 个人排行
        if (my.length) {
            this.tip.getComponent(cc.Label).string = `你的排名：第${my[0]['rank']}名`
        } else {
            this.tip.getComponent(cc.Label).string = '您尚未上榜'
        }
    }

    onItemClick(item: any) {
        let url: string = ''
        if (typeof window['wx'] == 'undefined') {
            url = item.url
        } else {
            AudioManager.instance.playSound(ENUM_AUDIO_CLIP.CLICK)
            url = item.appid
        }
        if (url) SdkManager.instance.turnToApp(url)
    }

    onCloseClick() {
        AudioManager.instance.playSound(ENUM_AUDIO_CLIP.CLICK)
        StaticInstance.uiManager.toggle(ENUM_UI_TYPE.RANK, false)
        StaticInstance.uiManager.toggle(ENUM_UI_TYPE.MENU)
    }

    onShareClick() {
        AudioManager.instance.playSound(ENUM_AUDIO_CLIP.CLICK)
        if (SdkManager.instance.getPlatform()) {
            SdkManager.instance.activeShare()
        } else {
            ToastManager.instance.show('仅支持小游戏平台', { gravity: 'TOP', bg_color: cc.color(226, 69, 109, 255) })
        }
    }

    onMenuClick(index: number) {
        this.menuIndex = index
        this.rendorMenu()
    }
}
